package com.softstao.guoyu.ui.fragment;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Handler;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.softstao.guoyu.R;
import com.softstao.guoyu.accept.Accept;
import com.softstao.guoyu.base.BaseFragment;
import com.softstao.guoyu.global.GsonManager;
import com.softstao.guoyu.global.SharePreferenceManager;
import com.softstao.guoyu.model.shop.Category;
import com.softstao.guoyu.model.shop.Goods;
import com.softstao.guoyu.model.shop.OrderProductInfo;
import com.softstao.guoyu.model.shop.ProductType;
import com.softstao.guoyu.model.shop.ShopIndex;
import com.softstao.guoyu.mvp.events.ActionEvent;
import com.softstao.guoyu.mvp.events.NotifyEvent;
import com.softstao.guoyu.mvp.interactor.shop.CartInteractor;
import com.softstao.guoyu.mvp.interactor.shop.GoodsInteractor;
import com.softstao.guoyu.mvp.presenter.shop.CartPresenter;
import com.softstao.guoyu.mvp.presenter.shop.GoodsPresenter;
import com.softstao.guoyu.mvp.rxbus.RxBus;
import com.softstao.guoyu.mvp.viewer.shop.AddCartViewer;
import com.softstao.guoyu.mvp.viewer.shop.CategoryViewer;
import com.softstao.guoyu.mvp.viewer.shop.GoodsListViewer;
import com.softstao.guoyu.ui.activity.MainActivity;
import com.softstao.guoyu.ui.activity.shop.CartActivity;
import com.softstao.guoyu.ui.activity.shop.OrderConfirmActivity;
import com.softstao.guoyu.ui.adapter.GoodsAdapter;
import com.softstao.softstaolibrary.library.utils.LZUtils;
import com.softstao.softstaolibrary.library.widget.BadgeView.BadgeView;
import com.softstao.softstaolibrary.library.widget.CustomScrollerView;
import com.softstao.softstaolibrary.library.widget.EmptyLayout;
import com.softstao.softstaolibrary.library.widget.FullyLinearLayoutManager;
import com.softstao.softstaolibrary.library.widget.LZToast;
import com.wangjie.androidinject.annotation.annotations.mvp.AIPresenter;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by vaikus on 2017/6/7.
 */

public class ShopFragment extends BaseFragment implements CategoryViewer, GoodsListViewer, GoodsAdapter.GoodsListener,AddCartViewer {

    @AIPresenter(presenter = GoodsPresenter.class, interactor = GoodsInteractor.class)
    GoodsPresenter presenter;
    @AIPresenter(presenter = CartPresenter.class,interactor = CartInteractor.class)
    CartPresenter cartPresenter;

    @BindView(R.id.category_view)
    LinearLayout categoryView;
    @BindView(R.id.goods_view)
    RecyclerView goodsView;
    @BindView(R.id.scroll_view)
    CustomScrollerView scrollView;
    @BindView(R.id.loading)
    RelativeLayout loading;
    @BindView(R.id.empty_layout)
    EmptyLayout emptyLayout;
    @BindView(R.id.scroll_view2)
    CustomScrollerView scrollView2;
    private List<Category> categoryList = new ArrayList<>();
    private List<Goods> goodsList = new ArrayList<>();
    private List<OrderProductInfo> orderProductInfos = new ArrayList<>();
    private GoodsAdapter goodsAdapter;
    private TextView[] textViews;
    private View[] views;
    private ImageView[] imgs;
    private int scrllViewWidth = 0, scrollViewMiddle = 0;
    private int typeId;
    private BadgeView cartBadge;

    @Override
    public int _ContentView() {
        return R.layout.fragment_shop;
    }

    @Override
    public void initView() {
        SharePreferenceManager.getInstance().setGoods(null,0);
        setTitleBar("商城");
        emptyLayout.setEmptyLayout(R.layout.layout_no_goods);
        scrollView2.setOnScrollChangedListener(this);
        titleBar.setRightIcon(R.mipmap.title_btn_cart);
        titleBar.setRightIconOnClick(v -> startActivity(new Intent(mContext, CartActivity.class)));

        presenter = new GoodsPresenter();
        presenter.setInteractor(new GoodsInteractor());
        presenter.setViewer(this);
        findCategory();

        goodsAdapter = new GoodsAdapter(goodsList);
        goodsAdapter.setGoodsListener(this);
        goodsView.setAdapter(goodsAdapter);
        goodsView.setLayoutManager(new FullyLinearLayoutManager(mContext));

        cartBadge = new BadgeView(mContext);
    }

    @OnClick({R.id.add_cart, R.id.buy_btn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.add_cart:
                if (SharePreferenceManager.getInstance().getGoods()!=null&&SharePreferenceManager.getInstance().getGoods().size()!=0){
                    for (int i=0;i<SharePreferenceManager.getInstance().getGoods().size();i++){
                        OrderProductInfo orderProductInfo = new OrderProductInfo();
                        orderProductInfo.setProductId(SharePreferenceManager.getInstance().getGoods().get(i).getProductId());
                        orderProductInfo.setCount(SharePreferenceManager.getInstance().getGoods().get(i).getBoxNum());
                        orderProductInfos.add(orderProductInfo);
                    }
                    addCart();
                }else {
                    LZToast.getInstance(mContext).showToast("请先选择商品");
                    return;
                }
                break;
            case R.id.buy_btn:
                if (SharePreferenceManager.getInstance().getGoods()!=null&&SharePreferenceManager.getInstance().getGoods().size()!=0){
                    startActivity(new Intent(mContext, OrderConfirmActivity.class));
                }else {
                    LZToast.getInstance(mContext).showToast("请先选择商品");
                    return;
                }
                break;
        }
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onLoad() {
        super.onLoad();
        findGoods();
    }

    private void showCategory() {
        textViews = new TextView[categoryList.size()];
        views = new View[categoryList.size()];
        imgs = new ImageView[categoryList.size()];
        categoryView.removeAllViews();
        categoryView.setOrientation(LinearLayout.VERTICAL);
        for (int i = 0; i < categoryList.size(); i++) {
            View view = ((LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.layout_category_item, null, false);
            view.setId(i);
            view.setOnClickListener(categoryListener);
            TextView textView = (TextView) view.findViewById(R.id.text);
            textView.setText(categoryList.get(i).getName());
            ImageView img = (ImageView) view.findViewById(R.id.img);
            Glide.with(mContext).load(categoryList.get(i).getImg()).into(img);
            textViews[i] = textView;
            views[i] = view;
            imgs[i] = img;
            categoryView.addView(view, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT));
        }
        changeTextColor(0);
        typeId = categoryList.get(0).getId();
        currentPage = 1;
        findGoods();
    }

    private View.OnClickListener categoryListener = v -> {
        changeTextColor(v.getId());
        changeTextLocation(v.getId());
        typeId = categoryList.get(v.getId()).getId();
        currentPage = 1;
        findGoods();
    };

    private void changeTextColor(int id) {
        for (int i = 0; i < textViews.length; i++) {
            if (i != id) {
                views[i].setBackgroundColor(Color.TRANSPARENT);
                textViews[i].setTextColor(getResources().getColor(R.color.font_gray));
            }
        }
        views[id].setBackgroundColor(getResources().getColor(R.color.white));
        textViews[id].setTextColor(getResources().getColor(R.color.font_pink));
    }

    /**
     * 改变栏目位置
     *
     * @param clickPosition
     */
    private void changeTextLocation(int clickPosition) {

        int x = (views[clickPosition].getTop() - getScrollViewMiddle() + (getViewheight(views[clickPosition]) / 2));
        scrollView.smoothScrollTo(0, x);
    }

    /**
     * 返回scrollview的中间位置
     *
     * @return
     */
    private int getScrollViewMiddle() {
        if (scrollViewMiddle == 0)
            scrollViewMiddle = getScrollViewheight() / 2;
        return scrollViewMiddle;
    }

    /**
     * 返回ScrollView的宽度
     *
     * @return
     */
    private int getScrollViewheight() {
        if (scrllViewWidth == 0)
            scrllViewWidth = scrollView.getBottom() - scrollView.getTop();
        return scrllViewWidth;
    }

    /**
     * 返回view的宽度
     *
     * @param view
     * @return
     */
    private int getViewheight(View view) {
        return view.getBottom() - view.getTop();
    }

    @Override
    public void findCategory() {
        presenter.getCategory(SharePreferenceManager.getInstance().getAgentId());
    }

    @Override
    public void getCategoryList(ProductType productType) {
        if (productType != null) {
            if (productType.getProductTypeList() != null && productType.getProductTypeList().size() != 0) {
                categoryList.clear();
                categoryList.addAll(productType.getProductTypeList());
                showCategory();
            }
        }
    }

    @Override
    public void findGoods() {
        loading.setVisibility(View.VISIBLE);
        presenter.getGoodsList(currentPage, SharePreferenceManager.getInstance().getAgentId(), typeId+"");
    }

    @Override
    public void getGoodsList(ShopIndex shopIndex) {
        loading.setVisibility(View.GONE);
        if (shopIndex != null) {
            if (shopIndex.getProductList() != null && shopIndex.getProductList().size() != 0) {
                emptyLayout.setVisibility(View.GONE);
                if (currentPage == 1) {
                    goodsList.clear();
                }
                goodsList.addAll(shopIndex.getProductList());
                goodsAdapter.notifyDataSetChanged();
            } else {
                if (currentPage == 1) {
                    emptyLayout.setVisibility(View.VISIBLE);
                }
            }
        }
    }

    @Override
    public void subtractPrice(int position, int preNumber, int number) {
        SharePreferenceManager.getInstance().setGoods(goodsList.get(position),-(preNumber-number));
    }

    @Override
    public void addPrice(int position) {
        SharePreferenceManager.getInstance().setGoods(goodsList.get(position),0);
    }

    @Override
    public void addCart() {
        loading.setVisibility(View.VISIBLE);
        cartPresenter.addCart(SharePreferenceManager.getInstance().getAgentId(), GsonManager.getInstance().getGson().toJson(orderProductInfos));
    }

    @Override
    public void addResult(Object result) {
        loading.setVisibility(View.GONE);
        SharePreferenceManager.getInstance().setGoods(null,0);
        goodsAdapter.notifyDataSetChanged();
        orderProductInfos.clear();
        new Handler().postDelayed(
                new Runnable() {
                    @Override
                    public void run() {
                        LZToast.getInstance(mContext).showToast("成功加入购物车");
                        ((MainActivity)getActivity()).findMessage();
                    }
                },500);
    }

    @Override
    public void error(Object tag, Object event) {
        super.error(tag, event);
        loading.setVisibility(View.GONE);
    }

    @Accept
    public void notifyEvent(Object tag, NotifyEvent event) {
        if(event.getCart_notify()!=0){
            cartBadge.setVisibility(View.VISIBLE);
            cartBadge.setTargetView(titleBar.getRightImageView());
            cartBadge.setBadgeMargin(0, 5, 0, 0);
            cartBadge.setTextSize(1);
            cartBadge.setText(" ");
            cartBadge.setHideOnNull(true);
            cartBadge.setmShowNumber(true);
            int padding = LZUtils.dipToPix(mContext, 2);
            int padding1 = LZUtils.dipToPix(mContext, 3);
            cartBadge.setPadding(padding1, padding, padding1, padding);
        }else {
            cartBadge.setVisibility(View.GONE);
        }
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
            RxBus.get().post(ActionEvent.SET_COLOR, 101);
        }
    }
}
